﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ExamDemo.Data;
using ExamDemo.ViewModel;

namespace ExamDemo.Controllers
{
    public class MessagesController : Controller
    {
        private ExamDemoDb db = new ExamDemoDb();

        // GET: Messages
        /// <summary>
        /// 说说首页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Index()
        {
            //if (Session["username"] == null)
            //{
            //    return Redirect("/Users/login");
            //}
            //else
            //{
                var userId = 1;
                //var currentUser = db.Users.Where(x => x.Id == userId).SingleOrDefault();

                var userList = db.Users.ToList();
                var msgList = db.Messages.ToList();
                var comList = db.Comments.ToList();

                var msgViewModelList = new List<ViewModel.Messages>();



                // 遍历所有的消息
                foreach (var msg in msgList)
                {
                    var tmpComList = new List<ViewModel.Comments>();
                    var currentMsgComments = comList.Where(x => x.MsgId == msg.Id).ToList();
                    foreach (var w in currentMsgComments)
                    {
                        tmpComList.Add(new ViewModel.Comments
                        {
                            FromUserName = userList.SingleOrDefault(x => x.Id == w.Id).Username,
                            ToUserName = userList.SingleOrDefault(x => x.Id == msgList.SingleOrDefault(t => t.Id == w.MsgId).FromUserId).Username,
                            Content = w.Content
                        });
                    }
                    msgViewModelList.Add(new ViewModel.Messages
                    {
                        Id = msg.Id,
                        FromUserId = msg.FromUserId,
                        Content = msg.Content,
                        Comments = tmpComList
                    });
                }
                var msgTestData = new TalkMessages
                {
                    //Username = currentUser.Username,
                    //倒序输出
                    Messages = msgViewModelList.OrderByDescending(x => x.Id)

                };
                return View();
            //};

        }

        /// <summary>
        /// 注销按钮
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            Session["username"] = null;
            return Json(new
            {
                code = 200,
                msg = "注销成功!"
            }
          );
        }

        /// <summary>
        /// 发表说说
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult Say(FormCollection collection)
        {
            var Content = collection["sayMsg"];
            var msgSay = db.Messages.Where(x => x.Content == Content);
            var userId = (int)Session["Id"];

            db.Messages.Add(new Models.Messages
            {
                Content = Content,
                FromUserId = userId,
            });
            db.SaveChanges();

            return Json(new
            {
                code = 200,
                msg = "发表成功！"
            });

        }

        /// <summary>
        /// 发表评论
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult Comment(FormCollection collection)
        {
            //if (Session["username"] == null)
            //{
            //    return Redirect("/Users/Login");
            //}
            //else
            //{
                //对数据库表评论内容的赋值
                var TalkContent = collection["commentMsg"];
                var ComTalk = db.Comments.Where(x => x.Content == TalkContent);

                var userList = db.Users.ToList();
                var msgList = db.Messages.ToList();
                var comList = db.Comments.ToList();

                //需要查询当前评论的说说Id
                foreach (var msg in msgList)
                {
                    //根据当前说说id，查找发送本条信息的User的id
                    var currentMsgUserId = userList.Where(x => x.Id == msg.Id);
                    //遍历当前说说的所有user id
                    foreach (var c in currentMsgUserId)
                    {
                        var ToId = msgList.SingleOrDefault(x => x.Id == comList.SingleOrDefault(t => t.Id == c.Id).MsgId).Id;
                        var UserId = (int)Session["Id"];
                        db.Comments.Add(new Models.Comments
                        {
                            Content = TalkContent,
                            MsgId = ToId,
                            FromUserId= UserId,
                            CreateAt = DateTime.Now,
                            UpdateAt = DateTime.Now,
                            Version = 0,
                        });
                    }
                }
                var comTestData = new ViewModel.Comments
                {
                    Content = TalkContent
                };

                db.SaveChanges();
                return Json(new
                {
                    code = 200,
                    msg = "评论成功！"
                });
            //}
        }
        public ActionResult logout()
        {
            return View("Users/login");
        }

        // GET: Messages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Models.Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // GET: Messages/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Messages/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FromUserId,Content,CreateAt,UpdateAt,Version,Remarks")] Models.Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Messages.Add(messages);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(messages);
        }

        // GET: Messages/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Models.Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FromUserId,Content,CreateAt,UpdateAt,Version,Remarks")] Models.Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Entry(messages).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(messages);
        }

        // GET: Messages/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Models.Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Models.Messages messages = db.Messages.Find(id);
            db.Messages.Remove(messages);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
